package auctionServer.businessLogic;

import java.util.Date;

public class Item {

	private int id;
	private Peer peer;
	private Date endDate;
	private String description;
	private int highest;
	private Peer higherBidder;
	
	public Item(int id, Peer peer, String description, Date date) {
		this.id = id;
		this.peer = peer;
		this.description = description;
		this.endDate = date;
		highest = 0;
		higherBidder = null;
	}
	

	public synchronized void auctionFinished() {
		if(higherBidder == null){
			peer.sendMessage("Item \'"+description+"\' has been fallen (no bidder)");
		}
		else{
			peer.sendMessage("Item \'"+description+"\' sold to "+higherBidder.getNick()+" wtih price " + highest);
			higherBidder.sendMessage("You have bought item \'"+description+"\' from "+peer.getNick()+" with price "+highest);
		}
	}

	
	public synchronized int getHighest() {
		return highest;
	}

	public synchronized void setHighest(int highest) {
		this.highest = highest;
	}

	public synchronized Peer getHigherBidder() {
		return higherBidder;
	}


	public synchronized void setHigherBidder(Peer higherBidder) {
		this.higherBidder = higherBidder;
	}


	public synchronized int getId() {
		return id;
	}

	public synchronized void setId(int id) {
		this.id = id;
	}

	public synchronized Peer getPeer() {
		return peer;
	}

	public synchronized void setPeer(Peer peer) {
		this.peer = peer;
	}

	public synchronized Date getEndDate() {
		return endDate;
	}

	public synchronized void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public synchronized String getDescription() {
		return description;
	}

	public synchronized void setDescription(String description) {
		this.description = description;
	}

	public String toString() {
		return id+". \'"+description+"\' "+peer.getNick()+" "+endDate+" "+highest+" "+(higherBidder==null?"none":higherBidder.getNick());
	}


	public synchronized void bid(Peer trier, int amount) {
		if(amount <= highest){
			trier.sendMessage("You unsuccessfully bid with "+amount+" on \'"+description+"\'. Current highest bid is "+highest+".");
			return;
		}
		if(higherBidder != null){
			higherBidder.sendMessage("Your higest bid on \'"+description+"\' is replaced with "+amount);
		}
		highest = amount;
		higherBidder = trier;
		higherBidder.sendMessage("You successfully bid with "+amount+" on \'"+description+"\'.");
	}
}
